<!--
 * 个人信息修改页面
-->
<template>
  <el-card class="card">
    <div style="text-align: center; margin-bottom: 30px"><b>修改个人信息</b></div>

    <el-form label-width="60px">
      <el-form-item label="头像">
        <el-upload class="avatar-uploader" action="#" :http-request="uploadAvatar" :show-file-list="false">
          <img v-if="form.avatarUrl" :src="form.avatarUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>

      <el-form-item label="用户名">
        <el-input v-model="form.username" autocomplete="off" :disabled="!editable"></el-input>
      </el-form-item>
      <el-form-item label="性别">
        <el-select v-model="form.gender" placeholder="请选择性别" :disabled="!editable">
          <el-option label="男" value="1"></el-option>
          <el-option label="女" value="0"></el-option>
        </el-select>
        <span v-if="!editable">{{ genderText }}</span>
      </el-form-item>
      <el-form-item label="电话">
        <el-input v-model="form.phone" autocomplete="off" :disabled="!editable"></el-input>
      </el-form-item>
      <el-form-item label="地址">
        <el-input v-model="form.address" autocomplete="off" :disabled="!editable"></el-input>
      </el-form-item>
      <el-button type="primary" style="margin-left: 190px; margin-top: 20px" @click="save">确 定</el-button> <el-button
        type="primary" style="margin-left: 190px; margin-top: 20px" @click="edit">编辑</el-button>
      <el-button type="primary" style="margin-left: 190px; margin-top: 20px" @click="goback">回到上一页</el-button>
    </el-form>
  </el-card>
</template>

<script>
import axios from 'axios'

export default {
  name: 'Person',
  data () {
    return {
      form: {
        username: '',
        avatarUrl: '',
        gender: '',
        phone: '',
        address: ''
      },
      // 不再需要headers属性，因为$http会自动处理认证
      editable: true // 控制用户名是否可编辑
    }
  },
  methods: {
    goback () {
      this.$router.go(-1)
      // this.$router.go(-1)
    },
    uploadAvatar (options) {
      // 创建FormData对象
      const formData = new FormData()
      formData.append('file', options.file)

      // 使用非异步方式处理上传，避免消息通道关闭问题
      this.$http.post('/file/upload', formData)
        .then(res => {
          if (res && res.code === 200) {
            // 更新头像URL
            this.form.avatarUrl = res.data
            this.$message.success('头像上传成功')
            options.onSuccess() // 确保调用成功回调
          } else {
            this.$message.error(res ? res.msg : '头像上传失败')
            options.onError(new Error(res ? res.msg : '头像上传失败')) // 提供错误对象
          }
        })
        .catch(error => {
          console.error('上传头像时出错:', error)
          this.$message.error('头像上传失败，请稍后重试')
          options.onError(error) // 传递错误对象
        })
    },
    edit () {
      this.editable = !this.editable
    },
    save () {
      // 构建与后端API匹配的用户数据对象
      const userData = {
        username: this.form.username,
        avatar: this.form.avatarUrl,
        sex: this.form.gender,
        phone: this.form.phone,
        address: this.form.address
      }

      // 获取当前用户ID
      const userInfo = JSON.parse(localStorage.getItem('user'))
      const userId = userInfo ? userInfo.id : null

      if (!userId) {
        this.$message.error('无法获取用户ID，请重新登录')
        return
      }

      // 使用Promise链式调用而不是async/await，避免消息通道关闭问题
      this.$http.put(`/user/${userId}`, userData)
        .then(res => {
          if (res && res.code === 200) {
            this.$message.success('保存成功')
            // 更新本地存储的用户信息
            const userInfo = {
              id: userId, // 保留ID
              username: this.form.username,
              avatar: this.form.avatarUrl,
              sex: this.form.gender,
              phone: this.form.phone,
              address: this.form.address
            }
            localStorage.setItem('user', JSON.stringify(userInfo))
            this.editable = false // 保存后禁用编辑
          } else {
            this.$message.error(res ? res.msg : '保存失败')
          }
        })
        .catch(error => {
          console.error('保存个人信息时出错:', error)
          this.$message.error('保存失败，请稍后重试')
        })
    },
    begin () {
      // 使用Promise链式调用而不是async/await，避免消息通道关闭问题
      this.$http.get('/user/token')
        .then(res => {
          console.log(res)
          if (res && res.code === 200) {
            // 只设置需要的字段，避免包含不需要的数据
            this.form = {
              username: res.data.username,
              avatarUrl: res.data.avatar,
              gender: res.data.sex, // 注意：后端字段是 sex，前端使用 gender
              phone: res.data.phone,
              address: res.data.address
            }

            // 确保性别值是正确的格式
            if (res.data.sex !== undefined) {
              // 将性别值转换为字符串类型，确保与select选项的value类型匹配
              this.form.gender = String(res.data.sex)
            }

            // 调试信息
            console.log('从后端获取的性别:', res.data.sex)
            console.log('设置到表单的性别:', this.form.gender)

            // 确保本地存储中有用户ID
            const userInfo = JSON.parse(localStorage.getItem('user')) || {}
            if (res.data.id && (!userInfo.id || userInfo.id !== res.data.id)) {
              // 更新本地存储中的用户ID
              userInfo.id = res.data.id
              localStorage.setItem('user', JSON.stringify(userInfo))
            }

            this.editable = false // 初始状态不可编辑
          } else {
            this.$message.error(res ? res.msg : '获取用户信息失败')
          }
        })
        .catch(error => {
          console.error('获取用户信息时出错:', error)
          this.$message.error('获取用户信息失败，请稍后重试')
        })
    }
  },
  created () {
    this.begin()
    /* const user = JSON.parse(localStorage.getItem('user'));
      if (user) {
        this.form = {
          ...user
        }; // 填充用户数据
      } */
  }
}

</script>

<style scoped>
  .card {
    width: 500px;
    margin: 80px auto;
    padding: 30px;
  }

  .avatar-uploader {
    padding-bottom: 10px;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 138px;
    height: 138px;
    line-height: 138px;
    text-align: center;
  }

  .avatar {
    width: 138px;
    height: 138px;
    display: block;
  }

</style>
